#!/bin/bash
ROOTFS="./"
INSTALL_DIR="$HOME/.local/bin"

detect_pkg_manager() {
    if command -v apt &>/dev/null; then echo "apt"
    elif command -v yum &>/dev/null; then echo "yum"
    elif command -v dnf &>/dev/null; then echo "dnf"
    elif command -v pacman &>/dev/null; then echo "pacman"
    elif command -v pkg &>/dev/null; then echo "termux"
    else echo "unknown"; fi
}

install_chroot() {
    case $(detect_pkg_manager) in
        apt) apt update && apt install -y debootstrap schroot ;;
        yum) yum install -y debootstrap schroot ;;
        dnf) dnf install -y debootstrap schroot ;;
        pacman) pacman -Sy --noconfirm debootstrap schroot ;;
        *) return 1 ;;
    esac
}

install_proot() {
    case $(detect_pkg_manager) in
        apt) apt update && apt install -y proot ;;
        yum) yum install -y proot ;;
        dnf) dnf install -y proot ;;
        pacman) pacman -Sy --noconfirm proot ;;
        termux) pkg install proot -y ;;
        *)
            mkdir -p "$INSTALL_DIR"
            wget -qO "$INSTALL_DIR/proot" "https://github.com/proot-me/proot/releases/latest/download/proot-$(uname -m)" || curl -L "https://github.com/proot-me/proot/releases/latest/download/proot-$(uname -m)" -o "$INSTALL_DIR/proot"
            chmod +x "$INSTALL_DIR/proot"
            echo "export PATH=\"\$PATH:$INSTALL_DIR\"" >> "$HOME/.bashrc"
            ;;
    esac
}

check_root() {
    [ "$(id -u)" -eq 0 ] && command -v chroot &>/dev/null
}

run_environment() {
    cd "$(dirname "$0")" || exit 1
    unset LD_PRELOAD

    if check_root; then
        chroot "$ROOTFS" /bin/bash -l
    else
        command="proot"
        command+=" --link2symlink"
        command+=" -0"
        command+=" -r $ROOTFS"
        command+=" -b /dev"
        command+=" -b /proc"
        command+=" -b /sys"
        command+=" -b $ROOTFS/root:/dev/shm"
        command+=" -w /root"
        command+=" /usr/bin/env -i"
        command+=" HOME=/root"
        command+=" PATH=/usr/local/sbin:/usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbin:/usr/games:/usr/local/games"
        command+=" TERM=$TERM"
        command+=" LANG=zh_CN.UTF-8"
        command+=" /bin/bash --login"
        com="$@"
        if [ -z "$1" ]; then
            exec $command
        else
            $command -c "$com"
        fi
    fi
}

check_installation() {
    if check_root; then
        command -v debootstrap &>/dev/null || install_chroot
    else
        command -v proot &>/dev/null || install_proot
    fi
}

check_installation && run_environment